<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>WeChat</h1>
<div>发送消息:</div>
<input type="text" id="msgContent">
<input type="button" value="点我发送" onclick="CHAT.chat()">
<div>接收消息:</div>
<div id="receiveMsg" style="background: darkgray"></div>

<script>

    window.CHAT = {
        socket: null,
        init: function () {
            if (!window.WebSocket) {
                alert("浏览器不支持websockt协议")
                return;
            }
            CHAT.socket = new WebSocket("ws://192.168.0.127:8088/ws")
            CHAT.socket.onopen = function () {
                console.log("连接建立成功...")
            }
            CHAT.socket.onclose = function () {
                console.log("连接关闭...")
            }
            CHAT.socket.onerror = function () {
                console.log("连接发生错误...")
            }
            CHAT.socket.onmessage = function (e) {
                console.log("接收到消息: "+e.data)
                const receiveMsg = document.getElementById("receiveMsg")
                const html = receiveMsg.innerHTML
                receiveMsg.innerHTML = html + "<br/>"+ e.data
            }
        },
        chat: function () {
            const msg = document.getElementById("msgContent")
            CHAT.socket.send(msg.value)
        }
    }
    CHAT.init()
</script>
</body>
</html>